package com.lzx.iteam.net;

import android.os.Message;
import android.util.Log;
import com.lzx.iteam.bean.WeeklyMsgBean;
import com.lzx.iteam.bean.WeeklyTemplate;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.StringUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class GetWeeklyCommentMsg extends CcMsgStructure {

    private Message mCallBack;

    public GetWeeklyCommentMsg(Message callback) {
        this.mCallBack = callback;
    }

    @Override
    public void onReceive(JSONObject data) {

        ArrayList<WeeklyMsgBean> datas = new ArrayList<WeeklyMsgBean>();
        try {
            JSONObject jsonObject = data.getJSONObject(AsynHttpClient.KEY_CC_DATA);
            if(jsonObject.has("msgs")){
                JSONArray jsonArray = jsonObject.getJSONArray("msgs");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject item = jsonArray.getJSONObject(i);
                    WeeklyMsgBean weeklyMsgBean = new WeeklyMsgBean();
                    weeklyMsgBean.setWeekly_id(item.getString("weekly_id"));
                    weeklyMsgBean.setGroup_id(item.getString("group_id"));
                    weeklyMsgBean.setComment_user_id(item.getString("comment_user_id"));
                    weeklyMsgBean.setComment_user_name(item.getString("comment_user_name"));
                    weeklyMsgBean.setComment_user_image(item.getString("comment_user_image"));
                    weeklyMsgBean.setComment_content(item.getString("comment_content"));
                    weeklyMsgBean.setComment_time(item.getString("comment_time"));
                    weeklyMsgBean.setWeekly_title(item.getString("weekly_title"));
                    weeklyMsgBean.setWeekly_content(item.getString("weekly_content"));
                    datas.add(weeklyMsgBean);
                }
            }

        } catch (JSONException e) {
            Log.d("GetWeeklyTemplateMsg", " error  === " + e.toString());
        }

        if (mCallBack != null) {
            mCallBack.obj = datas;
            mCallBack.arg1 = 0;
            mCallBack.sendToTarget();
            return;
        }
    }

    @Override
    public void onError(int error, Object ret) {
        String errorMsg = null;
        if (ret != null) {
            JSONObject jData = null;
            try {
                jData = new JSONObject(ret.toString());
                errorMsg = jData.getString("msg");
            } catch (JSONException e) {
                errorMsg = "服务端数据解析失败!";
                e.printStackTrace();
            }

        }
        if(mCallBack != null){
            mCallBack.arg1 = error;
            if(!StringUtil.isEmpty(errorMsg)){
                mCallBack.obj = errorMsg;
            }else{
                mCallBack.obj = Constants.NETWORK_WRROR;
            }
            mCallBack.sendToTarget();
        }
    }
}
